/* 
 * File:   VentanaPrincipal.cpp
 * Author: nahuel
 * 
 * Created on May 20, 2013, 8:24 PM
 */

#include "client_VentanaPrincipal.h"
#include "common_ClientConfFileManager.h"

#include <sstream>
#include <stdlib.h>

using namespace TP;

void VentanaPrincipal::InitValues() {
    ClientConfFileManager fileManager(_userHome.c_str());
    
    std::string pathAu = fileManager.GetPathAU();
    _pathAu->set_text(pathAu);    
    
    std::string ipServidor = fileManager.GetIpServidor();
    _ipServidor->set_text(ipServidor);
    
    std::string usuario = fileManager.GetUsuario();
    _usuario->set_text(usuario);
    
    std::string password = fileManager.GetPassword();
    _password->set_text(password);
    
    std::string puertoServidor = fileManager.GetPuertoServidor();    
    _puertoServidor->set_text(puertoServidor);
    
    unsigned int intervaloPolling = fileManager.GetIntervaloPolling();
    std::stringstream ss;
    ss << intervaloPolling;
    _intervaloPolling->set_text(ss.str());
}

VentanaPrincipal::VentanaPrincipal(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade) 
                    : Gtk::Window(cobject), _builder(refGlade) {
    char* home = getenv("HOME");
    
    if (home) {
        _userHome = std::string(home) + "/.au/config.xml";
    } else {
        _userHome = "/config.xml";
    }
    
    _builder->get_widget("EntryPathAU", _pathAu);
    _builder->get_widget("EntryIntervalo", _intervaloPolling);    
    _builder->get_widget("EntryIpServidor", _ipServidor);
    _builder->get_widget("EntryLabelPuertoServidor", _puertoServidor);
    _builder->get_widget("EntryUsuario", _usuario);
    _builder->get_widget("EntryPassword", _password);
    _builder->get_widget("BotonSave", _botonSave);
    
    InitValues();
    
    _botonSave->signal_clicked().connect(sigc::mem_fun(*this, &VentanaPrincipal::onSaveClick));    
    
    show_all_children(true);   
}

void VentanaPrincipal::onSaveClick() {
    std::string pathAu = _pathAu->get_text();
    std::string intervaloPollingStr = _intervaloPolling->get_text();
    std::string ipServidor = _ipServidor->get_text();
    std::string puertoServidor = _puertoServidor->get_text();
    std::string usuario = _usuario->get_text();
    std::string password = _password->get_text();
    
    unsigned int intervaloPolling;
    std::stringstream(intervaloPollingStr) >> intervaloPolling;    
    
    ClientConfFileManager fileManager(_userHome.c_str());
    
    fileManager.SetIntervaloPolling(intervaloPolling);
    fileManager.SetIpServidor(ipServidor);
    fileManager.SetPassword(password);
    fileManager.SetPathAU(pathAu);
    fileManager.SetPuertoServidor(puertoServidor);
    fileManager.SetUsuario(usuario);
    
    fileManager.SaveChanges();   
}

VentanaPrincipal::~VentanaPrincipal() {
    // TODO
}

